package cn.rongdao.jrkabao.ui.identify;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.util.ArrayMap;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.baidu.ocr.ui.camera.CameraActivity;
import com.mifengkong.frtools.http.request.callback.FRBaseObserver;
import com.mifengkong.frtools.ui.activity.FRStartActivity;
import com.mifengkong.frtools.util.FRCollection;
import com.mifengkong.frtools.util.FRString;
import com.mifengkong.frtools.util.FRToast;
import com.mifengkong.frtools.util.PictureUtil;
import com.mifengkong.frwidget.dialog.FRDialog;
import com.mifengkong.frwidget.dialog.FRDialogClickListener;
import com.mifengkong.frwidget.titlebar.TitleBarUIComponent;

import org.greenrobot.eventbus.EventBus;

import java.util.Map;

import butterknife.BindView;
import cn.rongdao.jrkabao.R;
import cn.rongdao.jrkabao.base.FRBaseTakePhotoActivity;
import cn.rongdao.jrkabao.bean.information.IdCardInfoByYituDistinguishBean;
import cn.rongdao.jrkabao.bean.takephoto.IdCardAndCheckIdentifyBean;
import cn.rongdao.jrkabao.constant.InfoConstant;
import cn.rongdao.jrkabao.model.takephoto.IdCardOCRModel;
import cn.rongdao.jrkabao.model.takephoto.UploadIdCardAndCheckIdentifyModel;
import cn.rongdao.jrkabao.ui.IdentificationVerificate.IdentifySuccessEvent;
import cn.rongdao.jrkabao.ui.cashadvance.CashAdvanceActivity;
import cn.rongdao.jrkabao.ui.cashadvance.addcard.AddCreditCardForCashActivity;
import cn.rongdao.jrkabao.ui.cashadvance.addcard.AddDepositCardActivity;
import cn.rongdao.jrkabao.ui.cashadvance.manager.LivenessManager;
import cn.rongdao.jrkabao.ui.deposit.account.MyAccountActivity;
import cn.rongdao.jrkabao.ui.takephoto.uicomponent.IdentifyUIComponent;
import cn.rongdao.jrkabao.util.CommonUtil;
import cn.rongdao.jrkabao.util.growingio.BuriedUtil;
import cn.rongdao.jrkabao.widget.CenterAlignImageSpan;


/**
 * Created by jack on 2017/10/9
 */

public class ProgressValidateIdCardActivity extends FRBaseTakePhotoActivity {

    public static final String DEPOSIT_TYPE = "deposit_type";    //提现过来的
    private static final String IS_CREDIT_FIRST = "is_credit_first";    //是否信用卡在前
    public static final String IS_PAIR = "is_pair";
    public static final String IS_FROM_MAIN = "is_from_main";

    public static void start(Context context, String institutionId, boolean isDeposit, boolean isCreditFirst, boolean isPair, boolean isFromMain) {
        Bundle bundle = new Bundle();
        bundle.putString(CashAdvanceActivity.INSTITUTION_ID, institutionId);
        bundle.putBoolean(DEPOSIT_TYPE, isDeposit);
        bundle.putBoolean(IS_CREDIT_FIRST, isCreditFirst);
        bundle.putBoolean(IS_PAIR, isPair);
        bundle.putBoolean(IS_FROM_MAIN, isFromMain);
        FRStartActivity.start(context, ProgressValidateIdCardActivity.class, bundle);
    }

    public static void start(Context context, String institutionId, boolean isCreditFirst, boolean isPair) {
        start(context, institutionId, false, isCreditFirst, isPair, false);
    }

    public static void start(Context context, boolean isDeposit, boolean isPair) {
        start(context, "", isDeposit, false, isPair, false);
    }

    public static void start(Context context, boolean isPair) {
        start(context, "", false, true, isPair, true);
    }

    @BindView(R.id.api_titlebar)
    TitleBarUIComponent titleBarUIComponent;
    @BindView(R.id.api_identify)
    IdentifyUIComponent identifyUIComponent;
    @BindView(R.id.ltipc_tv_next)
    TextView tvNext;

    private boolean isCreditFirst;
    private boolean isFromMain;
    private String institutionId;
    private boolean isDeposit;
    private int pictureSize;
    private boolean isPair;
    private String mHuman;//手持身份证的照片转Base64
    private String mReverse;//身份证背面的照片转Base64
    private String mObverse;//身份证正面的照片转Base64
    private Map<String, String> hashMap = new ArrayMap<>();
    private FRDialog frDialog;
    private LivenessManager livenessManager;
    private int code;

    @Override
    protected int layoutRes() {
        return R.layout.activity_progress_identify;
    }

    @Override
    protected void initView() {
        super.initView();
        BuriedUtil.kamao_yemian_jiazaiwancheng_apply(thisActivity(), 2);
        setAutoHideSoftInput(true);
        initDialog();
        livenessManager = new LivenessManager(this);
        livenessManager.initLivenessDialog(titleBarUIComponent);
        institutionId = getIntent().getStringExtra(CashAdvanceActivity.INSTITUTION_ID);
        isDeposit = getIntent().getBooleanExtra(DEPOSIT_TYPE, false);
        isPair = getIntent().getBooleanExtra(IS_PAIR, true);
        if (isPair) {
            if (!FRString.isEmpty(getIntent().getStringExtra(IS_PAIR))) {
                isPair = CommonUtil.isStatusSuccess(getIntent().getStringExtra(IS_PAIR));
            }
        }
        isCreditFirst = getIntent().getBooleanExtra(IS_CREDIT_FIRST, false);
        isFromMain = getIntent().getBooleanExtra(IS_FROM_MAIN, false);
        initTitleBar();
        identifyUIComponent.initData(this);
        initListener();
    }

    private void initDialog() {
        frDialog = new FRDialog.CommonBuilder(thisActivity())
                .setContentView(R.layout.dialog_confirm_identify)
                .setCancelableOutside(false)
                .setOnClickListener(R.id.dci_tv_confirm, new FRDialogClickListener() {
                    @Override
                    public boolean onDialogClick(View view) {
                        if (code == 2) {
                            code = 0;
                            frDialog.setText(R.id.dci_tv_confirm, "确认");
                            return true;
                        } else {
                            //点击确认
                            checkNameAndIdCard();
                            return false;
                        }
                    }
                })
                .create();
    }

    private void checkNameAndIdCard() {
        String name = ((EditText) frDialog.getView(R.id.dci_et_name)).getText().toString();
        String identifyId = ((EditText) frDialog.getView(R.id.dci_et_identify)).getText().toString();
        if (FRString.isEmpty(name, identifyId)) {
            FRToast.showToastSafe("请输入姓名和身份证号");
            return;
        }
        UploadIdCardAndCheckIdentifyModel.getInstance()
                .addParams("real_name", name)
                .addParams("identity_num", identifyId)
                .addParams(hashMap)
                .execute(new FRBaseObserver<IdCardAndCheckIdentifyBean>(this, "正在验证身份信息，请稍候...") {
                    @Override
                    protected void onBaseNext(IdCardAndCheckIdentifyBean data) {
                        code = data.getCode();
                        if (code == 0) {
                            frDialog.dismiss();
                            EventBus.getDefault().post(new IdentifySuccessEvent());
                            FRToast.showToastSafe("身份信息验证成功");
                            //身份验证完成，然后去绑定信用卡，再去绑定储蓄卡
                            if (!isPair) {
                                livenessManager.setInstitutionId(institutionId);
                                livenessManager.setIsMyAccount(isDeposit);
                                livenessManager.startLivenessActiviity(titleBarUIComponent);
                                livenessManager.setNeedFinish(true);
                            } else {
                                if (isDeposit) {
                                    MyAccountActivity.start(thisActivity());
                                } else {
                                    if (isCreditFirst) {
                                        AddCreditCardForCashActivity.start(thisActivity(), true, false, institutionId, isFromMain);
                                    } else {
                                        AddDepositCardActivity.start(thisActivity(), !isDeposit, false, institutionId, isFromMain);
                                    }
                                }
                                finish();
                            }
                        } else {
                            String errorMessage = data.getMessage();
                            if (code == 2) {
                                frDialog.setText(R.id.dci_tv_confirm, "重新拍照");
                            }
                            SpannableString ss = new SpannableString(FRCollection.appendAsString("# ", errorMessage, ""));
                            Drawable drawable = ContextCompat.getDrawable(thisActivity(), R.drawable.icon_identify_failure);
                            if (null != drawable) {
                                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                                CenterAlignImageSpan span = new CenterAlignImageSpan(drawable);
                                ss.setSpan(span, 0, 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                                frDialog.setText(R.id.dci_tv_error_msg, ss);
                            }
                        }
                    }
                });
    }

    private void initListener() {
        identifyUIComponent.setOnSelectIdentifyPicClickListener(new IdentifyUIComponent.OnSelectIdentifyPicClickListener() {
            @Override
            public void onSelectPicClick(int type, int picSize) {
                if (!lackPermission()) {
                    pictureSize = picSize;
                    picType = type;
                    switch (picType) {
                        case FRBaseTakePhotoActivity.PIC_WITHOUT_PERSON_FRONT:
                            Intent intent = new Intent(thisActivity(), CameraActivity.class);
                            intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                                    CommonUtil.getSaveFile(getApplication(), true).getAbsolutePath());
                            intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_FRONT);
                            startActivityForResult(intent, REQUEST_CODE_CAMERA);
                            break;
                        case FRBaseTakePhotoActivity.PIC_WITHOUT_PERSON_OPPOSITE:
                            intent = new Intent(thisActivity(), CameraActivity.class);
                            intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                                    CommonUtil.getSaveFile(getApplication(), false).getAbsolutePath());
                            intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_BACK);
                            startActivityForResult(intent, REQUEST_CODE_CAMERA);
                            break;
                        case FRBaseTakePhotoActivity.PIC_WITH_PERSON:
                            caremaOptionsDialog.show();
                            break;
                    }
                }
            }
        });

        tvNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(mObverse)) {
                    hashMap.put(InfoConstant.OBVERSE, mObverse);
                }
                if (!TextUtils.isEmpty(mReverse)) {
                    hashMap.put(InfoConstant.REVERSE, mReverse);
                }
                if (!TextUtils.isEmpty(mHuman)) {
                    hashMap.put(InfoConstant.HUMAN, mHuman);
                }
                checkOCR();
            }
        });
    }

    private void checkOCR() {
        IdCardOCRModel.getInstance().execute(hashMap.get(InfoConstant.OBVERSE), new FRBaseObserver<IdCardInfoByYituDistinguishBean>(this, "识别中，请稍候...") {
            @Override
            protected void onBaseNext(IdCardInfoByYituDistinguishBean data) {
                frDialog.setText(R.id.dci_et_name, FRString.valueOf(data.getName()));
                frDialog.setText(R.id.dci_et_identify, FRString.valueOf(data.getId_card()));
                frDialog.setText(R.id.dci_tv_error_msg, " ");
                frDialog.show();
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        livenessManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        livenessManager.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CAMERA && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                String contentType = data.getStringExtra(CameraActivity.KEY_CONTENT_TYPE);
                String filePath = "";
                String suffix;
                if (!FRString.isEmpty(contentType)) {
                    switch (contentType) {
                        case CameraActivity.CONTENT_TYPE_ID_CARD_FRONT:
                            filePath = CommonUtil.getSaveFile(getApplicationContext(), true).getAbsolutePath();
                            identifyUIComponent.setPositivePic(PictureUtil.getSmallBitmap(filePath));
                            mObverse = PictureUtil.bitmapToString(filePath);
                            break;
                        case CameraActivity.CONTENT_TYPE_ID_CARD_BACK:
                            filePath = CommonUtil.getSaveFile(getApplicationContext(), false).getAbsolutePath();
                            identifyUIComponent.setNegativePic(PictureUtil.getSmallBitmap(filePath));
                            mReverse = PictureUtil.bitmapToString(filePath);
                            break;
                    }
                    if (!FRString.isEmpty(filePath)) {
                        suffix = filePath.substring(filePath.lastIndexOf("."));
                        hashMap.put("suffix", suffix);
                    }
                }
                tvNext.setEnabled(isNextEnable());
            } else {
                FRToast.showToastSafe("选择图片文件不正确");
            }
        }
    }

    @Override
    protected void successReturnPicpath(String picPath, String suffix, String imageViewBase64) {
        hashMap.put("suffix", suffix);
        try {
            //将图片进行BASE64加密，然后再传输
            if (picType == PIC_WITH_PERSON) {
                mHuman = imageViewBase64;
                identifyUIComponent.setHandheldPic(picPath);
            }
            tvNext.setEnabled(isNextEnable());
        } catch (Exception e) {
            FRToast.showToastSafe("选择图片文件不正确");
        }
    }

    private boolean isNextEnable() {
        int flag = pictureSize;
        if (!FRString.isEmpty(mObverse)) {
            flag--;
        }
        if (!FRString.isEmpty(mReverse)) {
            flag--;
        }
        if (!FRString.isEmpty(mHuman)) {
            flag--;
        }
        return flag == 0;
    }

    private void initTitleBar() {
        titleBarUIComponent.initTitle("身份认证");
        titleBarUIComponent.setBackgroundColor(ContextCompat.getColor(thisActivity(), R.color.colorPrimary));
        titleBarUIComponent.initLeftBack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
}